<?php

namespace Celebrio\Diagnostics;

use Celebrio\WindowsAzure\AzureStorage\AzureStorageTable;
use LoggerLoggingEvent;
use Microsoft_WindowsAzure_Storage_DynamicTableEntity;
use Celebrio\Diagnostics\LoggerAppenderAzureTable;

/**
 * Celebrio Windows Azure storage table Timer appender for log4php
 *
 * @author Martin Novák
 */
class LoggerAppenderAzureTimer extends LoggerAppenderAzureTable {

    public function __construct() {
        parent::__construct();
        parent::setTable("log4phpTimer");
    }

    /**
     * Forwards the logging event to the destination.
     *
     * @param \LoggerLoggingEvent $event
     */
    protected function append(LoggerLoggingEvent $event) {
        parent::addEvent($this->formatTimer($event));
    }

    /**
     * Converts the timer logging event into an array which can be logged to Windows Azure storage table.
     * 
     * @param LoggerLoggingEvent $event
     * @return array The array representation of the logging event.
     */
    protected function formatTimer(LoggerLoggingEvent $event) {

        $eventValue = $event->getMessage();

        if (!is_array($eventValue) || count($eventValue) != 3)
            throw new \InvalidStateException("Event message must be an array with three elements: request ID, block, time");

        // yea... this is dirty but Windows Azure supports 1 KB rowkeys but the development storage does not
        if (AzureStorageTable::isDevelopmentStorage() && strlen($eventValue[1]) > 150) {
            $eventValue[1] = substr($eventValue[1], 0, 147) . "...";
        }

        /**
         * partition key is float with Unix timestamp with microseconds representing start of the request
         * row key is a watched code block with namaspace and class if available
         */
        $logEntity = new Microsoft_WindowsAzure_Storage_DynamicTableEntity($eventValue[0], rawurlencode($eventValue[1]));

        $logEntity->{'timestamp'} = date('Y m d H:i:s e');
        $logEntity->{'time'} = $eventValue[2];

        return $logEntity;
    }

}